<template>
	<div class="modal">
		<div class="bmain">
			<div class="mbody">
				<div class="search">
					<a-input v-model:value="searchText" @keyup.enter.stop="fuzzySearch(searchText)" v-bind="attrs" :style="{height:'32px',lineHeight:'32px'}"></a-input>
					<a-button :style="{ background: '#3f7fbf', margin: '0 5px', border: '0', color: '#fff' }"
						type="primary" @click="fuzzySearch(searchText)">搜索</a-button>
					<a-button :style="{ background: '#3f7fbf', border: '0', color: '#fff' }" type="primary"
						@click="resetSearch('')">重置</a-button>
				</div>
				<div class="transfer hhg-singleMember">
					<!-- 选择人员-tree类结构 -->
					<div class="tranleft singleMember" v-if="isTree">
						<div class="desc">{{ subTitle }}</div>
						<div class="lists">
							<a-tree
								v-model:value="value"
								style="width: 100%"
								:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
								:multiple="multiple"
								tree-default-expand-all
								ref="treeref"
								:selectedKeys="hhgSelectedKeys"
								@select="onSelect"
								:tree-data="leftList"
								tree-node-filter-prop="label"
								>
								<template #title="{ value: val, label }">
									<b v-if="val === 'parent 1-1'" style="color: #08c">{{ label }}</b>
									<template v-else>{{ label }}</template>
								</template>
							</a-tree>
						</div>
					</div>
					<!-- 选择人员-非tree类结构 -->
					<div class="tranleft singleMember" v-else>
						<div class="desc">{{ subTitle }}</div>
						<div class="lists" v-if="multiple">
							<div v-for="(item, index) in leftList" :key="item.id"
								class="listItem"
								:class="{ 'act': item.selected }"
								@click="selectListItemfn(item, $event, leftList)"
								@mousedown="startSelectionfn($event, index, leftList)"
								@mouseover="continueSelectionfn($event, index, leftList)"
								@mouseup="endSelectionfn($event)">
								<div class="listItemTxt">{{ item.displayName }}</div>
							</div>
						</div>
						<div class="lists" v-else>
							<div v-for="item in leftList" :key="item.id" :class="{ 'act': item.selected }"
								@click="selectItem(item)" class="listItem">
								<div class="listItemTxt">{{ item.displayName }}</div>
							</div>
						</div>
					</div>

					<div class="tranmid">
						<div class="listm">
							<p v-for="(item, index) in sortNum" :key="index" @click="selectLetters(item, index)" :class="[ index === currentIndex ? 'selected' : '' ]">{{ item }}</p>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="mfoot">
			<!-- 多选人员 -->
			<a-button :style="{ background: '#3f7fbf', border: '0', color: '#fff' }" type="primary"
				@click="selectedMemberMultiple" v-if="multiple">确定</a-button>
			<!-- 单选人员 -->
			<a-button :style="{ background: '#3f7fbf', border: '0', color: '#fff' }" type="primary"
				@click="selectedMemberSingle" v-else>确定</a-button>
			<a-button :style="{ background: '#3f7fbf', border: '0', color: '#fff', margin: '0 12px' }"
				type="primary" @click="clearList">清空</a-button>
			<a-button :style="{ background: '#dddddd', border: '0', color: '#666' }"
				@click="closeModal">关闭</a-button>
		</div>
	</div>
</template>
<script setup>
import { message } from "ant-design-vue"
import { ref, defineEmits, defineProps, watch, useAttrs, onMounted } from 'vue'
import { selectListItem, startSelection, endSelection, continueSelection, mergeAndSetSelected, EventBus } from './utils'
//父组件传过来的值
const props = defineProps({
	config: {
		type: Object,
		default: () => { },
		multiple: {
			type: Boolean,
			require: false,
			default: false
		},
		subTitle: {
			type: String,
			require: false,
			default: () => ''
		},
		list: {
			type: Array,
			require: false,
			default: () => []
		}
	}
})
//属性穿透
const attrs = useAttrs()

const currentIndex = ref(0)
//监听父组件传来的数据
const isTree = ref(props.config.isTree)
//测试数据
const allList = ref([])
const leftList = ref([])
const subTitle = ref('')
watch(() => props.config, (val) => {
	if (val) {
		allList.value = val.list
		leftList.value = val.list
		subTitle.value = val.subTitle
		if (val.displayList) {
			// 遍历数组 displayList
			val.displayList.forEach(itemB => {
				// 在 allList 中查找具有相同 id 的元素
				const match = leftList.value.find(itemA => itemA.id === itemB.id)
				// 如果找到了匹配项，则将它的 selected 属性设置为 true
				if (match) {
					match.selected = true
				}
			})
		}
	}
}, { immediate: true }, { deep: true })
//多选人员设置
const multiple = ref(props.config?.multiple)
const selectListItemfn = (item, event, list)=> {
	return selectListItem(item, event, list)
}
const startSelectionfn = (event, index, list)=> {
	return startSelection(event, index, list)
}
const endSelectionfn = (event)=> {
	return endSelection(event)
}
const continueSelectionfn = (event, index, list)=> {
	return continueSelection(event, index, list)
}
//单选人员的方法
const selectItem = item => {
	leftList.value = leftList.value.map(i => {
		i.selected = false
		return i
	})
	item.selected = true
}

const type = ref(props.config.type ? props.config.type : 1)
const searchText = ref('')
const emit = defineEmits(['selectedMember', 'closeModal', 'clearRight', 'clearMebmer', 'fuzzySearch'])
//搜索
const letters = ref('ALL')
const fuzzySearch = (text) => {
	emit('fuzzySearch', { text, letters: letters.value})
}
const resetSearch = (text) => {
	letters.value = 'ALL'
	searchText.value = ''
	currentIndex.value = -1
	emit('fuzzySearch', { text, letters: letters.value})
}
const selectLetters = (lett, index)=> {
	currentIndex.value = index
	letters.value = lett
	emit('fuzzySearch', { text: searchText.value, letters: lett})
}

//选择人员-单选
const selectedMemberSingle = () => {
	const data = isTree.value ? treeList.value : leftList.value.filter(item => item.selected)
	localStorage.setItem('localMember', JSON.stringify(mergeAndSetSelected(JSON.parse(localStorage.getItem('localMember')), data)))
	
	if (data === undefined || data && data.length === 0) {
		message.warning('请选择数据')
		return
	}
	if (type.value === 1) {
		emit('selectedMember', {
			name: data.map(i => i.displayName).join(','),
			code: data.map(i => i.id).join(','),
			data
		})
	}
	if (type.value === 2) {
		emit('selectedMember', {
			name: data.map(i => i.displayName).join(','),
			code: data.map(i => i.id).join(','),
			data
		})
	}
}
const treeList = ref([])
const hhgSelectedKeys = ref([])
const onSelect = (selectedKeys, e)=> {
	treeList.value = e.selectedNodes
	hhgSelectedKeys.value = selectedKeys
}
//选择人员-多选
const selectedMemberMultiple = () => {
	const data = isTree.value ? treeList.value : leftList.value.filter(item => item.selected)
	localStorage.setItem('localMember', JSON.stringify(mergeAndSetSelected(JSON.parse(localStorage.getItem('localMember')), data)))
	if (data === undefined || data && data.length === 0) {
		message.warning('请选择数据')
		return
	}
	if (type.value === 1) {
		emit('selectedMember', {
			name: data.map(i => i.displayName).join(','),
			code: data.map(i => i.code).join(','),
			data
		})
	}
	if (type.value === 2) {
		emit('selectedMember', {
			name: data.map(i => i.displayName).join(','),
			code: data.map(i => i.code).join(','),
			data
		})
	}
}
const closeModal = () => {
	emit('closeModal')
}
const clearList = () => {
	leftList.value.map(item => {
		item.selected = false
		return item
	})
	emit('clearMebmer')
}
//生成26个大写字母
function generateAlphabet() {
	const alphabet = ['ALL']
	for (let i = 65; i <= 90; i++) {
		alphabet.push(String.fromCharCode(i))
	}
	return alphabet
}
const sortNum = ref(generateAlphabet())

onMounted(()=> {
	EventBus.on('radioSinglePopup', ()=> {
		hhgSelectedKeys.value = []
		currentIndex.value = 0
	})
})
</script>
<style scoped lang="scss"></style>